package top.ibase4j.core.support.context;

import com.weibo.api.motan.config.ProtocolConfig;
import com.weibo.api.motan.config.RefererConfig;

@SuppressWarnings("unchecked")
public class MotanContext {
    private static ProtocolConfig motanProtocol;
    private static com.weibo.api.motan.config.RegistryConfig motanRegistry;

    @SuppressWarnings("rawtypes")
    public static <T> T getService(Class<T> cls) {
        if (motanProtocol == null || motanRegistry == null) {
            synchronized (MotanContext.class) {
                if (motanProtocol == null) {
                    motanProtocol = ApplicationContextHolder.getBean(ProtocolConfig.class);
                }
                if (motanRegistry == null) {
                    motanRegistry = ApplicationContextHolder.getBean(com.weibo.api.motan.config.RegistryConfig.class);
                }
            }
        }
        // 引用远程服务
        RefererConfig reference = new RefererConfig<>();
        reference.setProtocol(motanProtocol);
        reference.setRegistry(motanRegistry); // 多个注册中心可以用setRegistries()
        reference.setInterface(cls);
        reference.setCheck("false");
        return (T)reference.getRef();
    }
}
